package com.tanhua.dubbo.api.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.UserLocation;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        if(ObjectUtil.isEmpty(userLocation)) {
            //数据不存在,进行插入操作
            userLocation = new UserLocation();
            userLocation.setId(ObjectId.get());
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());

            this.mongoTemplate.save(userLocation);

        } else {
            //数据已存在,进行更新操作

            UpdateDefinition update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                    .set("address", address)
                    .set("updated", System.currentTimeMillis())
                    .set("lastUpdated", userLocation.getLastUpdated());
            this.mongoTemplate.updateFirst(query, update, UserLocation.class);
        }
        return true;
    }

    @Override
    public UserLocationVo queryByUserId(Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId));

        return UserLocationVo.format(this.mongoTemplate.findOne(query, UserLocation.class));
    }

    @Override
    public PageInfo<UserLocationVo> queryUserFromLocation(Double longitude,
                                                          Double latitude,
                                                          Double distance,
                                                          String gender,
                                                          Integer page,
                                                          Integer pageSize) {
        PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("location")));
        Distance distanceObj = new Distance(distance / 1000, Metrics.KILOMETERS);
        Circle circle = new Circle(new GeoJsonPoint(longitude, latitude), distanceObj);
        Query query = Query.query(Criteria.where("location")
                .withinSphere(circle))
                .with(pageRequest);
        List<UserLocation> userLocationList = this.mongoTemplate.find(query, UserLocation.class);
        //判断性别是否符合要求,不符合要求的从集合中删除
        List<UserLocation> userLocationList_gender = new ArrayList<>();
        for (UserLocation userLocation : userLocationList) {
            String queryGender = this.userInfoApi.queryGender(userLocation.getUserId());
            if(StrUtil.equals(gender, queryGender)) {
                userLocationList_gender.add(userLocation);
            }
        }
        //若集合为空,直接返回
        if(ObjectUtil.isEmpty(userLocationList_gender)) {
            return pageInfo;
        }
        // TODO 按照距离排序 实现思路：根据坐标进行计算 目标点与 我的点的距离  按照距离进行排序


        pageInfo.setRecords(UserLocationVo.formatList(userLocationList_gender));
        return pageInfo;
    }
}
